<template>

    <div class="table-responsive table-scrollable no-padding-bottom">
        <table class="table table-striped table-bordered table-hover dataTable no-footer">
            <thead>
                <tr style="background-color: #E4EAEC;">
                    <th style="vertical-align: middle;width:5%;text-align: center;padding: 0px;border-right-width: 0px;" v-if="settings.showCheckBox">
                        <div class="form-group form-md-checkboxes" style="margin: 0px;">
                            <div class="md-checkbox-inline" style="margin: 0px;">
                                <div class="md-checkbox">

                                    <label class="i-checks m-b-none i-checks-sm" @click="allRowClick()">
                                        <input type="checkbox" v-model="allRowChecked"><i></i>
                                    </label>

                                </div>
                            </div>
                        </div>
                    </th>
                    <th v-for="key in columns"
                        :class="{active: sortKey == key.field}" v-bind:style="{width:key.width}" @click="sortBy(key.field)">
                        {{key.name | capitalize}}
                      <span class="arrow"
                            :class="sortOrders[key.field] > 0 ? 'asc' : 'dsc'">
                      </span>
                    </th>
                    <th v-if="rowEvents.show" v-bind:style="{width:rowEvents.width}" style="text-align: center">操作</th>
                </tr>
            </thead>
            <tbody>

                <tr v-for="
                    item in rows
                    | filterBy filterKey
                    | orderBy sortKey sortOrders[sortKey]">

                    <td style="vertical-align: middle;width:5%;text-align: center;padding: 0px;border-right-width: 0px;" v-if="settings.showCheckBox">
                        <div class="form-group form-md-checkboxes" style="margin: 0px;">
                            <div class="md-checkbox-inline" style="margin: 0px;">
                                <div class="md-checkbox">

                                    <label class="i-checks m-b-none i-checks-sm">
                                        <input type="checkbox" v-model="item.checked" name="check" @click="rowClick(item)"><i></i>
                                    </label>

                                </div>
                            </div>
                        </div>
                    </td>

                    <td v-for="key in columns">
                        <a @click="key.clickEvent(item)" class="{{key.class}}" v-if="key.clickEvent">
                            {{item[key.field]}}</a>
                        <span v-if="!key.clickEvent && !key.colorEvent">{{item[key.field]}}</span>
                        <span v-if="!key.clickEvent && key.colorEvent" v-bind:style="{color:key.colorEvent(item[key.field],item)}">{{item[key.field]}}</span>
                    </td>

                    <td v-if="rowEvents.show" style="text-align: center;">
                        <button type="button" style="padding: 3px 8px; margin-right:3px;"
                                class="btn btn-default {{button.class}}"
                                v-for="button in rowEvents.events"
                                @click="button.click(item)" title="{{button.name}}">
                            {{button.name}}
                        </button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <footer class="panel-footer no-border no-padding-top" style="padding-right: 0">
        <div class="text-right">
            <ul class="pagination">
                <li class="paginate_button" @click="reLoadData()">
                    <a href="javascript:void(0)" class="refresh" style="color: #2f3342;"><i class="fa fa-refresh"></i></a>
                </li>
                <li class="paginate_button previous {{params.page.prevPageDisabled}}"
                    @click="pageNumberClick('prev')">
                    <a href="javascript:void(0)"><i class="fa fa-angle-left"></i></a>
                </li>
                <li v-for="pageNumber in params.page.pageNumbers"
                    class="paginate_button {{pageNumber.active}} {{pageNumber.disabled}}"
                    @click="pageNumberClick(pageNumber.number)">
                    <a href="javascript:void(0)">{{pageNumber.number}}</a>
                </li>
                <li class="paginate_button next {{params.page.nextPageDisabled}}"
                    @click="pageNumberClick('next')"><a href="javascript:void(0)"><i
                        class="fa fa-angle-right"></i></a>
                </li>
                <li class="paginate_button disabled"><a href="javascript:void(0)">{{params.page.totalRecords}}条/{{params.page.totalPages}}页</a></li>
            </ul>
        </div>
    </footer>


</template>
<style lang="sass">
    th{
        cursor: pointer;
    }
    .arrow {
        display: inline-block;
        vertical-align: middle;
        width: 0;
        height: 0;
        margin-left: 5px;
        opacity: 0.66;
        /*background-color: #00b3ee;*/
    }

    .arrow.asc {
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-bottom: 4px solid #00b3ee;
    }

    .arrow.dsc {
        margin-top: 9px;
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-top: 4px solid #00b3ee;
    }
</style>
<script>

    import dbFetch from '../services/dbFetch'
    import lang from 'lodash/lang'

    export default{
        replace: true,
        props: {
            datas:{
                type: Array,
                default: function _default() {
                    return [];
                }
            },
            fieldEvents:{
                type: Object,
                default: function _default() {
                    return {};
                }
            },
            rowEvents:{
                type: Object,
                default: function _default() {
                    return {};
                }
            },
            dataUrl:{
                type: String,
                default: function _default() {
                    return '';
                },
                required: true
            },
            columns:{
                type: Array,
                default: function _default() {
                    return [];
                },
                required: true
            },
            filterKey:{
                type: String,
                default: function _default() {
                    return 'query search';
                }
            },
            settings:{
                type: Object,
                default: function _default() {
                    return {};
                }
            }
        },
        data(){
            var sortOrders = {}
            this.columns.forEach(function (key) {
                sortOrders[key.field] = 1
            })
            return {
                sortKey: '',
                sortOrders: sortOrders,
                rows:[],
                params:{
                    page : {
                        pageNumber: 1,
                        pageSize: this.settings.pageSize || 10,
                        prevPageDisabled: 'disabled',
                        nextPageDisabled: 'disabled'
                    }
                },
                queryparams:{}
            }
        },
        ready (){

            this.loadData();
        },
        computed :{
            allRowChecked: {
                get: function(){
                    return false;
                },
                set: function(value){
                    this.rows.map(function(item){
                        item.checked = value
                    })
                    return value;
                }
            }
        },
        methods:{
            sortBy (key) {
                this.sortKey = key
                this.sortOrders[key] = this.sortOrders[key] * -1
            },
            loadData () {
                var that = this;

                this.queryParams = lang.clone(this.params);

                this.queryParams["page"] = {
                    pageNumber: this.params.page.pageNumber ? this.params.page.pageNumber : 1,
                    pageSize: this.params.page.pageSize
                };

                if(this.datas.length){
                    this.rows = this.datas;
                }else{
                    dbFetch.fetchGet(this.dataUrl,this.queryParams, function (res) {
                        console.log(res);

                        res.responseBody.content.map(function(row){

                            that.columns.map(function(v,i){
                                var value = (row[v.field] || "");
                                if(!lang.isUndefined(that.fieldEvents)){

                                    var colorEvent = that.fieldEvents[v.field + 'Color'];
                                    colorEvent ? v.colorEvent = colorEvent : function (){};

//                                    var clickEvent = that.fieldEvents[v.field + 'Click'];
//                                    clickEvent ? v.clickEvent = clickEvent : function (){};

                                    var formatEvent = that.fieldEvents[v.field + 'Format'];
                                    formatEvent ? v.formatEvent = formatEvent : function (){};
                                }

                                //格式化数据
                                if (v.formatEvent) {
                                    value = v.formatEvent(value, row);
                                }
                                row[v.field] = value;

                            });

                            row.checked = false;
                        });
                        that.rows = res.responseBody.content;

                        //分页数据处理
                        var pages = {};
                        pages.totalRecords = res.responseBody.totalElements;
                        pages.pageNumber = res.responseBody.pageNumber;
                        pages.pageSize = res.responseBody.pageSize;
                        pages.totalPages = res.responseBody.totalPages;

                        var totalPage = pages.totalPages;
                        //分页算法，页面只显示固定数量的分页按钮。
                        var pageNumbers = [];
                        var startPage = 1;
                        var endPage = totalPage;
                        var pageStep = 2;//以当前页为基准，前后各显示的页数量
                        if (totalPage >= 6) {
                            startPage = pages.pageNumber;
                            if (startPage >= pageStep) {
                                startPage -= pageStep;
                            }
                            if (startPage <= 1) {
                                startPage = 1;
                            }
                            endPage = (totalPage - pages.pageNumber) >= pageStep ? pages.pageNumber + pageStep : totalPage;
                            if (endPage > totalPage) {
                                endPage = totalPage;
                            }
                            if (startPage != 1) {
                                pageNumbers.push({number: "1"});
                                if (startPage - 1 != 1) {
                                    pageNumbers.push({number: "...", disabled: "disabled"});
                                }
                            }
                        }
                        for (var i = startPage; i <= endPage; i++) {
                            if (i == pages.pageNumber) {
                                pageNumbers.push({number: i, active: "active"});
                            } else {
                                pageNumbers.push({number: i});
                            }
                        }
                        if (endPage != totalPage) {
                            if (endPage + 1 != totalPage) {
                                pageNumbers.push({number: "...", disabled: "disabled"});
                            }
                            pageNumbers.push({number: totalPage});
                        }
                        pages.pageNumbers = pageNumbers;
                        if (pages.pageNumber == 1 || pages.totalPages == 0) {
                            pages.prevPageDisabled = "disabled";
                        }
                        if (pages.pageNumber == totalPage || pages.totalPages == 0) {
                            pages.nextPageDisabled = "disabled";
                        }

                        that.params.page = pages;

                        console.log(that.params.page.pageNumbers);


                    });
                }
            },
            reLoadData () {
                this.params.page.pageNumber = 1;
                this.loadData();
            },
            allRowClick () {

            },
            pageNumberClick (pageNumber) {

                var prevPage = this.params.page.prevPageDisabled;
                if (pageNumber === "prev" && prevPage && prevPage != "") {
                    return false;
                }
                var nextPage = this.params.page.nextPageDisabled;
                if (pageNumber === "next" && nextPage && nextPage != "") {
                    return false;
                }
                if (pageNumber == this.params.page.pageNumber) {
                    return false;
                }
                if (pageNumber === "...") {
                    return false;
                }
                if (pageNumber === "prev") {
                    this.params.page.pageNumber--;
                } else if (pageNumber === "next") {
                    this.params.page.pageNumber++;
                } else {
                    this.params.page.pageNumber = pageNumber;
                }

                this.loadData();
            },
            rowClick (item) {
                item.checked = !item.checked;
//                console.log(item.checked)
            },
            getData () {

                var rowsArr = [];

                this.rows.map(function (val) {
                    if(val.checked){
                        rowsArr.push(val);
                    };
                });

                return rowsArr;
            }
        }
    }
</script>
